package y24.m1.exam;

public class Test1 {
    public static void main(String[] args) {
        int numerator = 4; // 分子
        int denominator = 5; // 分母

        // 转换为二进制定点数
        String fixedPoint = fractionToFixedPoint(numerator, denominator);
        System.out.println("二进制定点数：" + fixedPoint);

        // 转换为浮点数
        String floatingPoint = fractionToFloatingPoint(fixedPoint);
        System.out.println("浮点数：" + floatingPoint);

        // 原码
        String original = fractionToOriginal(fixedPoint);
        System.out.println("原码：" + original);

        // 补码
        String twosComplement = fractionToTwosComplement(fixedPoint);
        System.out.println("补码：" + twosComplement);

        // 反码
        String onesComplement = fractionToOnesComplement(fixedPoint);
        System.out.println("反码：" + onesComplement);
    }

    // 将分数转换为二进制定点数
    public static String fractionToFixedPoint(int numerator, int denominator) {
        double fraction = (double) numerator / denominator;
        long bits = Double.doubleToRawLongBits(fraction);
        String binary = Long.toBinaryString(bits >> 52);
        return binary;
    }

    // 将二进制定点数转换为浮点数
    public static String fractionToFloatingPoint(String fixedPoint) {
        long bits = Long.parseLong(fixedPoint, 2);
        double fraction = Double.longBitsToDouble(bits << 52);
        return Double.toString(fraction);
    }

    // 将二进制定点数转换为原码
    public static String fractionToOriginal(String fixedPoint) {
        StringBuilder original = new StringBuilder();

        for (int i = 0; i < fixedPoint.length(); i++) {
            original.append(fixedPoint.charAt(i) == '1' ? '1' : '0');
        }
        return original.toString();
    }

    // 将二进制定点数转换为补码
    public static String fractionToTwosComplement(String fixedPoint) {
        StringBuilder twosComplement = new StringBuilder();

        for (int i = 0; i < fixedPoint.length(); i++) {
            twosComplement.append(fixedPoint.charAt(i) == '1' ? '0' : '1');
        }
        return twosComplement.toString();
    }

    // 将二进制定点数转换为反码
    public static String fractionToOnesComplement(String fixedPoint) {
        StringBuilder onesComplement = new StringBuilder();

        for (int i = 0; i < fixedPoint.length(); i++) {
            onesComplement.append(fixedPoint.charAt(i) == '1' ? '0' : '1');
        }
        return onesComplement.toString();
    }
}
